package com.lvmama.system.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.lvmama.autoconfig.ConfigManager;
import com.lvmama.entity.system.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.common.StringTools;
import com.lvmama.entity.system.CommonType;
import com.lvmama.entity.system.Menu;
import com.lvmama.system.service.MenuService;

@Controller
public class MenuController extends BaseController{
	@Autowired
	private MenuService menuService;
	@Value("#{'${default.pageSize}'}")
	private String pageSize;
    @Autowired
    private ConfigManager configManager;

	
	/**
     * 菜单首页分页查询
     * @param user
     * @return
     */
	@RequestMapping("/menuList")
    public String list(ModelMap model,HttpServletRequest request,String page) 
	{
		int size = Integer.valueOf(pageSize);
		String pageNum = request.getParameter("page");
		pageNum = StringTools.isValid(pageNum) ? pageNum:"0";
		PageInfo<Menu> pageInfo= menuService.findAllPageList(Integer.valueOf(pageNum), size);
        model.addAttribute("page", pageInfo);
        model.addAttribute("menus", pageInfo.getList());

        return "/system/menuList";
    }
	/**
     * 获取所有菜单
     * @param user
     * @return
     */
	@RequestMapping("/newMenu")
    public String newMenu(Model model) {
        List<Menu> menus = menuService.findAllList();
        List<Config> configList = configManager.showAllConfig();
        JSONArray menuJson = new JSONArray();
        for (Menu menu : menus) {
            JSONObject node = new JSONObject();
            node.put("id", menu.getId());
            if("1".equals(menu.getParentId())){
                node.put("pId", menu.getSysCode());
            }else{
                node.put("pId", menu.getParentId());
            }
            node.put("name", menu.getName());
            node.put("open", true);
            menuJson.add(node);
        }
        //增加系统节点 虚拟节点
        List<String> sysCodeList = getAllSysCode(configList);
        for(String sysCode : sysCodeList){
            JSONObject node = new JSONObject();
            node.put("id", sysCode);
            node.put("pId", "1");
            node.put("name", getSysNameByCode(sysCode, configList));
            node.put("open", true);
            menuJson.add(node);
        }

        CommonType[] getIsShowType = CommonType.getIsShowType();
        CommonType[] getDelFlagType = CommonType.getDelFlagType();
        List<CommonType> isShowList = Arrays.asList(getIsShowType);
        List<CommonType> delFlagList = Arrays.asList(getDelFlagType);
        model.addAttribute("isShowList", isShowList);
        model.addAttribute("delFlagList", delFlagList);
        model.addAttribute("menus", menuJson.toJSONString());
        Menu menu = new Menu();
        menu.setIsShow("1");
        Menu pmenu = new Menu();
        menu.setParent(pmenu);
        model.addAttribute("menu", menu);
        model.addAttribute("newtext", true);
        return "/system/menuForm";
    }
	
	/**
     * 编辑权限
     * 
     * @param model
     * @return
     */
    @RequestMapping("/editMenu")
    public String editMenu(Model model, String id) {
        CommonType[] getIsShowType = CommonType.getIsShowType();
        CommonType[] getDelFlagType = CommonType.getDelFlagType();
        List<CommonType> isShowList = Arrays.asList(getIsShowType);
        List<CommonType> delFlagList = Arrays.asList(getDelFlagType);
        Menu menu=new Menu();
        menu.setId(id);
        menu.setSort(null);
        menu.setIsShow(null);
        menu.setDelFlag(CommonType.ENABLE.getStringValue());
        menu=menuService.selectMenu(menu);
        model.addAttribute("newtext", false);
        model.addAttribute("isShowList", isShowList);
        model.addAttribute("delFlagList", delFlagList);
        model.addAttribute("menu", menu);
        return "/system/menuForm";
    }
    /**
     * 保存权限
     * 
     * @param role
     * @param model
     * @param redirectAttrs
     * @return
     */
    @RequestMapping("/saveMenu")
    public String saveMenu(Menu menu, Model model,String isShowNew,String permissionNew,String iconNew,String parentId, String microServiceId) {
        menu.setIsShow(isShowNew);
        menu.setPermission(permissionNew);
        menu.setIcon(iconNew);
        menu.getParent().setId(parentId);
        menu.setSysCode(microServiceId);
        menuService.insertOrUpdateMenu(menu);
        return "redirect:/menuList";
    }
    /**
     * 查询父级权限信息
     * 
     * @return
     */
    @RequestMapping("/getParent" )
    @ResponseBody
    public Object getParent(String nodeHtml){
        List<Config> configList = configManager.showAllConfig();
        Map<String, Object> result = new HashMap();
        Menu menu=new Menu();
        menu.setName(nodeHtml);
        menu.setSort(null);
        menu.setIsShow(CommonType.ENSHOW.getStringValue());
        menu.setDelFlag(CommonType.ENABLE.getStringValue());
        menu=menuService.selectMenu(menu);

        result.put("code", "1");
        List<String> icons = menuService.selectIcons();
        result.put("icons", icons);

        if(null == menu){//一定是虚拟节点
            String sysCode = getSysCodeByName(nodeHtml, configList);
            //将根节点返回去
            Menu root = new Menu();
            root.setId("1");
            root.setSort(0);
            root = menuService.selectMenu(root);
            result.put("sysCode", sysCode);
            result.put("msg", root);
            return result;
        }

        if("功能菜单".equals(nodeHtml)){
            result.put("code", "-1");
            result.put("msg", "无法在根节点创建权限！");
            return result;
        }


        result.put("msg", menu);
        result.put("sysCode", menu.getSysCode());
        return result;

    } 


    private String getSysNameByCode(String sysCode, List<Config> configList){
        for(Config config : configList){
            if(sysCode.equals(config.getSyscode())){
                return config.getValuedesc();
            }
        }
        return "权限系统";
    }

    private String getSysCodeByName(String sysName, List<Config> configList){
        for(Config config : configList){
            if(sysName.equals(config.getValuedesc())){
                return config.getSyscode();
            }
        }
        return "server";
    }
}
